import PikaStdLib
import PikaStdDevice
#import machine
import os
import time
import aht20_unittest

#---
import network, socket, json
import _thread, eventloop, fsm
import PikaDebug

import pika_lvgl

def utest():
    suit = unittest.TestSuite("test1")
    suit.addTest(aht20_unittest.AHT20UnitTest())
    runner = unittest.TextTestRunner()
    res = runner.run(suit)

def wifi_init():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect('Roberto','kcf#1234')
    for i in range(10):
        if wlan.isconnected():
            print('wifi connected')
            return
        time.sleep(1)
        print('wifi connecting...', i)
        

def socket_connect():
    wifi_init()
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('192.168.1.161',8080))
    print('socket connected')
    client.send('hello'.encode())
    return client


def aht20_upload():
    client = socket_connect()
    aht = aht20.AHT20()
    temp, humi = aht.read()
    message_dict = {'temp': temp, 'humi': humi}
    message_json = json.dumps(message_dict)
    client.send(message_json.encode())    

def aht20_wait_request():
    client = socket_connect()
    while True:
        recv_str = client.recv(1024).decode()
        print('recv: ', recv_str)
        if recv_str== 'exit':
            break
        recv_dict = json.loads(recv_str)

        if 'fun' not in recv_dict:
            print('fun not in recv_dict')
            continue
        
        if recv_dict['fun'] == 'request_aht20':
            aht = aht20.AHT20()
            temp, humi = aht.read()
            message_dict = {
                'fun': 'response_aht20',
                'ret': {
                    'temp': temp,
                    'humi': humi
                    }
                }
            message_json = json.dumps(message_dict)
            client.send(message_json.encode())
            
        
print('hello pikapython!')
mem = PikaStdLib.MemChecker()
print('mem used max:')
mem.max()
print('mem used now:')
mem.now()
